package lib.self.fresco;

import android.app.ActivityManager;
import android.content.Context;
import android.net.Uri;
import androidx.annotation.DrawableRes;
import android.util.AttributeSet;

import com.facebook.cache.disk.DiskCacheConfig;
import com.facebook.common.internal.Supplier;
import com.facebook.drawee.backends.pipeline.Fresco;
import com.facebook.drawee.view.SimpleDraweeView;
import com.facebook.imagepipeline.cache.DefaultBitmapMemoryCacheParamsSupplier;
import com.facebook.imagepipeline.cache.MemoryCacheParams;
import com.facebook.imagepipeline.core.ImagePipelineConfig;
import com.facebook.imagepipeline.listener.RequestListener;
import com.facebook.imagepipeline.listener.RequestLoggingListener;

import java.io.File;
import java.util.HashSet;
import java.util.Set;

import lib.self.ConstEx;
import lib.self.fresco.provider.BaseProvider;
import lib.self.fresco.provider.FrescoProvider;
import lib.self.fresco.renderer.BaseRenderer;
import lib.self.fresco.renderer.BlurRenderer;
import lib.self.fresco.renderer.CircleRenderer;
import lib.self.fresco.renderer.CornerRenderer;

/**
 * description: 加载图片控件
 * author: Steven Xiao
 * date: 2017/4/27
 */
public class NetworkImageView extends SimpleDraweeView {
    private BaseProvider mProvider;

    public NetworkImageView(Context context) {
        super(context);
        init(context);
    }

    public NetworkImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    public NetworkImageView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init(context);
    }

    private void init(Context context) {
        mProvider = new FrescoProvider(context, this);
    }

    public void load(String url) {
        load(url, 0, null);
    }

    public void load(String url, BaseRenderer renderer) {
        load(url, 0, renderer);
    }

    public void load(String url, @DrawableRes int placeHolderRid) {
        load(url, placeHolderRid, null);
    }

    /**
     * @param url
     * @param placeHolderRid
     * @param param          {@link BlurRenderer} / {@link CircleRenderer} / {@link CornerRenderer}
     */
    public void load(String url, @DrawableRes int placeHolderRid, BaseRenderer param) {
        mProvider.load(url, placeHolderRid, param, ConstEx.KInvalidValue);
    }

    public void load(int fadeDuration, String url) {
        load(fadeDuration, url, 0, null);
    }

    public void load(int fadeDuration, String url, BaseRenderer renderer) {
        load(fadeDuration, url, 0, renderer);
    }

    public void load(int fadeDuration, String url, @DrawableRes int placeHolderRid) {
        load(fadeDuration, url, placeHolderRid, null);
    }

    public void load(int fadeDuration, String url, @DrawableRes int placeHolderRid, BaseRenderer param) {
        mProvider.load(url, placeHolderRid, param, fadeDuration);
    }

    /**
     * 设置图片加载监听
     *
     * @param listener
     */
    public void setListener(NetworkImageListener listener) {
        mProvider.setListener(listener);
    }

    /**
     * 初始化, 直接调用对应provider的初始化方法
     *
     * @param context
     * @param cacheDir           文件保存路径
     * @param maxMemoryCacheSize 最大内存使用数, 单位: byte
     */
    public static void init(Context context, String cacheDir, final int maxMemoryCacheSize) {
        if (cacheDir == null) {
            return;
        }

        DiskCacheConfig diskCacheConfig = DiskCacheConfig.newBuilder(context)
                .setBaseDirectoryPath(new File(cacheDir))
                .build();

        Supplier<MemoryCacheParams> supplier = new DefaultBitmapMemoryCacheParamsSupplier((ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE)) {

            @Override
            public MemoryCacheParams get() {
                return new MemoryCacheParams(
                        maxMemoryCacheSize,
                        256,
                        Integer.MAX_VALUE,
                        Integer.MAX_VALUE,
                        Integer.MAX_VALUE);
            }
        };


        Set<RequestListener> requestListeners = new HashSet<>();
        requestListeners.add(new RequestLoggingListener());
        ImagePipelineConfig config = ImagePipelineConfig.newBuilder(context)
                .setMainDiskCacheConfig(diskCacheConfig)
                .setBitmapMemoryCacheParamsSupplier(supplier)
                .setDownsampleEnabled(true)
                .setRequestListeners(requestListeners)
//                .setCacheKeyFactory(cacheDir)
//                .setEncodedMemoryCacheParamsSupplier(encodedCacheParamsSupplier)
//                .setExecutorSupplier(executorSupplier)
//                .setImageCacheStatsTracker(imageCacheStatsTracker)
//                .setMemoryTrimmableRegistry(memoryTrimmableRegistry)
//                .setNetworkFetchProducer(networkFetchProducer)
//                .setPoolFactory(poolFactory)
//                .setProgressiveJpegConfig(progressiveJpegConfig)
//                .setRequestListeners(requestListeners)
//                .setSmallImageDiskCacheConfig(smallImageDiskCacheConfig)
                .build();
        Fresco.initialize(context, config);
    }

    /**
     * 清理内存中cache
     */
    public static void clearMemoryCache() {
        Fresco.getImagePipeline().clearMemoryCaches();
    }

    public static void clearCaches() {
        Fresco.getImagePipeline().clearCaches();
    }

    /**
     * 清除指定的缓存
     *
     * @param url
     */
    public static void clearFromCache(String url) {
        Uri uri = Uri.parse(url);
        Fresco.getImagePipeline().evictFromCache(uri);
        Fresco.getImagePipeline().evictFromDiskCache(uri);
    }
}
